import React, { useState, useEffect, useRef } from 'react'
import { Button, Input, Space, Modal, Table, Checkbox, Row, Col, Radio, Select, message } from 'antd';
import { SettingOutlined, DownOutlined, UpOutlined, FormOutlined, CloudUploadOutlined, CloudDownloadOutlined, ArrowUpOutlined, ArrowDownOutlined } from '@ant-design/icons';
import './../btn.css'
import AdvancedSearch from './../advancedSearch/AdvancedSearch';
import CustomersImport from './../customersImport/CustomersImport';
import store from '../../../redux/store';
import myAxios from '../../../utils/myAxios';
import { AsyncTableDataAction } from '../../../redux/action/customerAction/tableData';
export default function SetTting() {
  const myInput = useRef()
  useEffect(() => {
    //统计各客户类型数据条数
    myAxios({
      method: 'get',
      url: '/customer/findCountCustomerInformation'
    })
      .then(res => {
        // console.log(res.data);
        let oData = res.data.data
        settypeCount([
          { status: 1, num: oData.countToDayCustomerInformation },
          { status: 2, num: oData.countToWeekCustomerInformation },
          { status: 3, num: oData.countToMouthCustomerInformation },
        ])
        setCustomerClass(oData.typeList)
        setstatusCount([
          { status: 1, num: oData.已成交 },
          { status: 4, num: oData.有意向 },
          { status: 5, num: oData.潜在客户 },
          { status: 3, num: oData.确定细节 },
          { status: 2, num: oData.等待打款 },
        ])
      })
  }, [])

  //统计各客户类型数据条数 (今日新增，本周，本月)
  const [typeCount, settypeCount] = useState([]);
  //统计各客户类型数据条数 (成交，等待打款。。。。。)
  const [statusCount, setstatusCount] = useState([]);

  const [isDown, setisDown] = useState(true);
  //高级搜索的状态
  const [search, setsearch] = useState(false);
  //导入的状态
  const [isShowImport, setisShowImport] = useState(false);

  //规定一个状态，来控制是升序还是降序   1：升序 2 ：降序
  const [rise, setrise] = useState(1);

  const [isShowModal, setisShowModal] = useState(false);
  //修改字段模态框
  const [ismodifyField, setmodifyField] = useState(false);
  const [fieldName, setfieldName] = useState('');

  //单选
  const [value, setValue] = useState(1);
  const [value2, setValue2] = useState(1);
  const [isProtect, setisProtect] = useState(false);
  const [currentBtn, setcurrentBtn] = useState(null);
  const [currentRank, setcurrentRank] = useState(null);
  const [dateTypeIndex, setdateTypeIndex] = useState(null);
  const dateType = [{ reqStatus: 1, title: '今日新增' }, { reqStatus: 2, title: '本周新增' }, { reqStatus: 3, title: '本月新增' },]
  //默认为请求客户列表。
  const [findTime, setfindTime] = useState(0);
  //默认为不需要排序
  const [sort, setsort] = useState(0);
  //客户类型
  const [reqcustomerType, setreqcustomerType] = useState(null);

  const [rankRule, setrankRule] = useState([
    { reqStatus: 1, title: '编号' }, { reqStatus: 2, title: '录入时间' }, , { reqStatus: 3, title: '更新时间' }
  ]);
  const CheckboxGroup = Checkbox.Group;
  const plainOptions = ['Apple', 'Pear', 'Orange'];
  const defaultCheckedList = ['Apple', 'Orange'];

  const [checkedList, setCheckedList] = useState(defaultCheckedList);
  const [indeterminate, setIndeterminate] = useState(true);
  const [CustomerClass, setCustomerClass] = useState([]);
  const columns = [
    {
      title: '字段名称',
      dataIndex: 'fieldsName',
      key: 'fieldsName'
    },
    {
      title: '显示名称',
      dataIndex: 'showName',
      key: 'showName',
      render: (showName) => {
        return <>
          {showName}<FormOutlined onClick={() => modifyField(showName)} style={{ 'color': "#577cc1", "cursor": "pointer" }} />
        </>
      }
    },
    {
      title: '列表显示',
      dataIndex: 'listShow',
      key: 'listShow',
      render: (listShow, a) => {
        return <Checkbox defaultChecked={listShow} onChange={(e) => {
          console.log(e);
          listShowOnchange(a, listShow)
        }} ></Checkbox>
      }
    },
    {
      title: '是否必填',
      dataIndex: 'isRequire',
      key: 'isRequire',
      render: (isRequire) => {
        return <Checkbox defaultChecked={isRequire} onChange={isRequireOnchange}></Checkbox>
      }
    },
  ];

  const data = [
    {
      key: 'customer',
      fieldsName: '客户名称',
      showName: '客户名称',
      listShow: 1,
      isRequire: 0,
    },
    {
      key: 'contact',
      fieldsName: '联系人',
      showName: '联系人',
      listShow: 1,
      isRequire: 1,
    },
    {
      key: 'jobType',
      fieldsName: '职位',
      showName: '职位',
      listShow: 0,
      isRequire: 1,
    }, {
      key: 'phone',
      fieldsName: '手机号码',
      showName: '手机号码',
      listShow: 0,
      isRequire: 1,
    },
    {
      key: 'qq',
      fieldsName: 'QQ',
      showName: 'QQ',
      listShow: 0,
      isRequire: 1,
    },
    {
      key: 'email',
      fieldsName: '电子邮箱',
      showName: '电子邮箱',
      listShow: 0,
      isRequire: 1,
    }, {
      key: 'birthday',
      fieldsName: '生日',
      showName: '生日',
      listShow: 0,
      isRequire: 1,
    }, {
      key: 'region',
      fieldsName: '所在地区',
      showName: '所在地区',
      listShow: 0,
      isRequire: 1,
    },
    {
      key: 'address',
      fieldsName: '详细地址	',
      showName: '详细地址	',
      listShow: 0,
      isRequire: 1,
    },
    {
      key: 'postcode',
      fieldsName: '邮编',
      showName: '详细地址	',
      listShow: 0,
      isRequire: 1,
    },
    {
      key: 'customerType',
      fieldsName: '客户类型',
      showName: '详细地址	',
      listShow: 0,
      isRequire: 1,
    },
    {
      key: 'customerLevel',
      fieldsName: '客户级别',
      showName: '客户级别	',
      listShow: 0,
      isRequire: 1,
    },
    {
      key: 'customerSource',
      fieldsName: '客户来源',
      showName: '客户来源	',
      listShow: 0,
      isRequire: 1,
    },
    {
      key: 'profession',
      fieldsName: '所属行业',
      showName: '所属行业	',
      listShow: 0,
      isRequire: 1,
    },
    {
      key: 'goodsType',
      fieldsName: '商品类别',
      showName: '商品类别	',
      listShow: 0,
      isRequire: 1,
    },
    {
      key: 'url',
      fieldsName: '网址',
      showName: '网址',
      listShow: 0,
      isRequire: 1,
    },
    {
      key: 'comment',
      fieldsName: '备注',
      showName: '备注	',
      listShow: 0,
      isRequire: 1,
    },
  ];
  const [customerType, setcustomerType] = useState([{ id: 1, name: '已成交' }, { id: 2, name: '待付款' }, { id: 3, name: '确定细节' }, { id: 4, name: '有意向' }, { id: 5, name: '潜在客户' }]);
  //修改字段
  const modifyField = (showName) => {
    console.log(showName);
    setfieldName(showName)
    setmodifyField(true)
  }
  // 列表展示
  const listShowOnchange = (a, listShow) => {
    // console.log(e.target.checked);
    console.log(listShow);
    console.log(a);

  }
  // 是否必填
  const isRequireOnchange = (e) => {
    console.log(e.target.checked);
  }

  const handleImport = () => {
    setisShowImport(false);
  };

  const handleCancelImport = () => {
    setisShowImport(false);
  };

  const handleOk = () => {
    setisShowModal(false);
  };

  const handleCancel = () => {
    setisShowModal(false);
  };
  const showModal = () => {
    setisShowModal(true)
  };
  function cancelProtect() {
    setisProtect(false)
  }
  const onChangeRadio = e => {
    console.log('radio checked', e.target.value);
    setValue(e.target.value);
  };
  const onChangeRadio2 = e => {
    console.log('radio checked', e.target.value);
    setValue2(e.target.value);
  };

  const onChange = list => {
    setCheckedList(list);
    setIndeterminate(!!list.length && list.length < plainOptions.length);
  };
  const changerise = () => {
    if (rise == 1) {
      setrise(2)
    } else {
      setrise(1)
    }
  }
  //普通搜索
  const commonSearch = () => {
    // console.log(myInput.current.input.value);
    //普通搜索输入的内容
    let ordinaryInformation = myInput.current.input.value
    //发起普通搜索请求
    let obj = { type: 2, page: 1, limit: 7, ordinaryInformation }
    store.dispatch(AsyncTableDataAction(1, 7, 0, 0, 1, '', 2, ordinaryInformation))
    // myAxios({
    //   method: 'post',
    //   url: '/customer/findLikeCustomer',
    //   data: obj
    // })
    //   .then(res => {
    //     console.log(res.data);
    //     /* if (res.data.code !== 200) {
    //       message.success('')
    //     } */
    //   })
  }


  return (
    <>
      <Row>
        <Col span={12}>
          <div>
            <Space>
              <Space>
                {
                  dateType.map((item, index) =>
                    <Button
                      size='middle'
                      key={index}
                      type="primary"
                      className={index == dateTypeIndex ? 'btn-bgc-active' : 'btn-bgc-unactive'}
                      onClick={() => {
                        setdateTypeIndex(index)
                        setfindTime(item.reqStatus)
                        //请求table数据
                        // getTableData()
                        store.dispatch(AsyncTableDataAction(1, 7, item.reqStatus, sort, rise, reqcustomerType,0))
                      }}

                    >{item.title}

                      {
                        typeCount.map(item2 => {
                          return item.reqStatus == item2.status ? <span key={item2.status} style={{
                            marginLeft: '5px', color: '#505152', backgroundColor: '#ccc', width: '20px'
                          }}>{item2.num}</span> : ""
                        })
                      }

                    </Button>
                  )
                }
              </Space>
              <Space>
                <Button
                  onClick={() => setisShowImport(!isShowImport)}
                  icon={<CloudUploadOutlined />} type='primary' style={{ backgroundColor: '#5C7B9A' }}>数据导入</Button>
                <Button
                  onClick={() => { setsearch(!search) }}
                  icon={<CloudDownloadOutlined />} type='primary' style={{ backgroundColor: '#5C7B9A' }}>数据导出</Button>
              </Space>
            </Space>
          </div>
          {/* 导入 */}
          <Modal title="数据到入"
            bodyStyle={{ height: '620px' }}
            centered
            destroyOnClose={true}
            confirmLoading={true}
            footer={null}
            width={window.innerWidth * 0.7}
            visible={isShowImport} onOk={handleImport} onCancel={handleCancelImport}>
            <CustomersImport />
          </Modal>
        </Col>
        <Col span={12}>
          <div style={{ paddingBottom: '10px', textAlign: 'right', backgroundColor: 'white' }}>
            <Space style={{ height: '30px' }}  >
              <Button size='small' icon={<SettingOutlined />} style={{ marginRight: '10px', backgroundColor: '#a1a3a5', color: 'white' }} onClick={() => { showModal() }} >自定义设置</Button>
              <Button onClick={() => { setisProtect(true) }} size='small' icon={<SettingOutlined />} style={{ backgroundColor: '#469F8E', color: 'white' }} >保护期设置</Button>
              <Input ref={myInput} size='small' placeholder="客户名称 联系人 手机号码" />
              <Button
                onClick={commonSearch}
                type="primary" style={{ marginRight: '10px' }} size='small'>搜索</Button>
              <Button onClick={() => {
                setisDown(!isDown)
                setsearch(!search)
              }} type="primary" danger size='small'>高级搜索 {isDown ? <DownOutlined /> : <UpOutlined />} </Button>
            </Space>
            {/* 自定义设置 */}
            <Modal
              bodyStyle={{ height: 520, overflowY: 'scroll' }} centered title="自定义设置" visible={isShowModal} onOk={handleOk} onCancel={handleCancel}>
              <Table columns={columns} dataSource={data} pagination={false} />

              <Modal title="修改字段显示名称" visible={ismodifyField} onOk={() => setmodifyField(false)} onCancel={() => setmodifyField(false)}>
                <Space>
                  <span>显示名称：</span>
                  <Input value={fieldName} />
                </Space>
                <div style={{ textAlign: 'center', color: 'red', fontSize: '18px', fontWeight: '900' }}>
                  <p>字段名称(含自定义字段)不要重复！</p>
                  <p>否则导出会报错！</p>
                </div>
              </Modal>
            </Modal>

          </div>
        </Col>
      </Row >
      {
        search ? <AdvancedSearch /> : ''
      }

      <Row>
        <Space>
          <Col >
            <Space >
              {
                CustomerClass.map((item, index) => (
                  <Button style={{ backgroundColor: index == currentBtn ? '' : '#F0F2F5' }} size='small' type={index == currentBtn ? 'primary' : ''} key={index} onClick={() => {
                    setcurrentBtn(index)
                    setreqcustomerType(item.title)
                    //请求table数据
                    store.dispatch(AsyncTableDataAction(1, 7, findTime, sort, rise, item.title,0))
                  }} >{item.title}
                    {
                      statusCount.map(element => {
                        return item.id == element.status ? <span key={element.status}>({element.num})</span> : ''
                      })
                    }
                  </Button>
                ))
              }
            </Space>
          </Col>
          <Col>
            <Space >
              {
                rankRule.map((item, index) => (
                  <Button size='small' danger key={index} type={index == currentRank ? 'primary' : ''} onClick={() => {
                    setcurrentRank(index)
                    setsort()
                    changerise()
                    //请求table数据
                    store.dispatch(AsyncTableDataAction(1, 7, findTime, item.reqStatus, rise, reqcustomerType,0))

                  }} >{item.title} {rise == 1 ? <ArrowUpOutlined /> : <ArrowDownOutlined />}</Button>
                ))
              }
            </Space>
          </Col>
        </Space>
        <div style={{ flex: '1', textAlign: 'right', backgroundColor: 'white' }}>
          <span>客户数量限制：</span>
          <span className='font-color-red'>7</span>
          <span className='font-color-red'>/ 无限制</span>
        </div>
      </Row >
      {/* 保护期设置 */}
      <Modal visible={isProtect} onCancel={cancelProtect}
        width={700}
        footer={[]}
        title='保护期设置'
      >
        <div style={{ fontWeight: 'bolder', textAlign: 'center' }}>保护期规则设置</div>
        <Space style={{ height: 100, border: '1px solid gray', width: '100%' }}>
          <div style={{ width: 100 }}>保护期规则:</div>
          <Space>
            <Space>
              <div style={{ width: 50 }}><Input></Input></div>
              <div>天内</div>
            </Space>
            <Radio.Group onChange={onChangeRadio2} value={value2}>
              <Space direction="vertical">
                <Radio value={1}><span >无新增跟单</span></Radio>
                <Radio value={2}><span>无订单或合同</span></Radio>
                <Radio value={3}><span>禁用该功能</span></Radio>
              </Space>
            </Radio.Group>
          </Space>
          <span> , 这个客户将自动释放到公海 </span>
        </Space>
        <Space style={{ height: 100, border: '1px solid gray', width: '100%' }}>
          <div style={{ width: 100 }}>自动客户类型:</div>
          <Space>
            <Radio.Group onChange={onChangeRadio} value={value}>
              <Space direction="vertical">
                <Radio value={1}><span >新增跟单或合同后</span></Radio>
                <Radio value={3}><span>禁用该功能</span></Radio>
              </Space>
            </Radio.Group>
            <span>,自动将【客户类型】变更为</span>
            <Select defaultValue='已成交' style={{ width: '170px' }}>
              {
                customerType.map((item) =>
                  <Select.Option key={item.id} value={item.name}>{item.name}</Select.Option>
                )
              }
            </Select>
          </Space>
        </Space>
        <Space style={{ height: 100, border: '1px solid gray', width: '100%' }}>
          <div style={{ width: 100 }}>客户类型排除:</div>
          <CheckboxGroup options={plainOptions} value={checkedList} onChange={onChange} />
        </Space>

        <div style={{ textAlign: 'center', borderTop: '1px dashed gray', padding: 20 }}>
          <Space>
            <Button style={{ width: 100 }} size='midle' type="primary" htmlType="submit"
              onClick={() => setisProtect(false)}
            >
              保存
            </Button>
            <Button onClick={() => { setisProtect(false) }} style={{ width: 100 }} size='midle' danger type="primary" >
              取消
            </Button>
          </Space>
        </div>
      </Modal>
    </>
  )
}
